<?php

namespace addons\epay\controller;

use addons\epay\library\Service;
use app\api\controller\User;
use fast\Random;
use think\addons\Controller;
use Exception;
use think\Db;
use think\Cache;

/**
 * 微信支付宝整合插件首页
 *
 * 此控制器仅用于开发展示说明和测试，请自行添加一个新的控制器进行处理返回和回调事件，同时删除此控制器文件
 *
 * Class Index
 * @package addons\epay\controller
 */
class Index extends Controller
{
    public $AppId = 'wxbae1b3248b60e1d8';

    protected $layout = 'default';

    protected $config = [];

    public function _initialize()
    {
        parent::_initialize();
        // if (!config("app_debug")) {
        //     $this->error("仅在开发环境下查看");
        // }
    }


    /**
     * 发送post请求
     */
    function json_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

    public function index()
    {
        $this->view->assign("title", "微信支付宝整合");
        return $this->view->fetch();
    }

    /**
     * 体验，仅供开发测试
     */
    public function experience()
    {
        $amount = $this->request->post('amount');
        $type = $this->request->post('type');
        $method = $this->request->post('method');
        $openid = $this->request->post('openid', "");

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }

        if (in_array($method, ['miniapp', 'mp']) && !$openid) {
            $this->error("openid不能为空");
        }

        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);

        //订单标题
        $title = '测试订单';

        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method, $openid);

        return $response;
    }

    /**
     * 支付成功，仅供开发测试
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
    

    /**
     * 支付成功【微信小程序】
     */
    public function notifyOrder()
    {
        file_put_contents("111222333get.txt",var_export($_GET,true),FILE_APPEND);
        file_put_contents("111222333post.txt",var_export($_POST,true),FILE_APPEND);
        // $token = '01MaMSiAqg5JidQR7C4vTNAPORcSsx31';
        // $signature = $_GET["signature"];
        // $timestamp = $_GET["timestamp"];
        // $nonce = $_GET["nonce"];
        // $echostr = $_GET["echostr"];
        // $tmpArr = array($token, $timestamp, $nonce);
        // sort($tmpArr, SORT_STRING);
        // $tmpStr = implode( $tmpArr );
        // $tmpStr = sha1( $tmpStr );
        // if ($tmpStr == $signature ) {
        //     file_put_contents("121212122122222.txt",111111);
        //     return $echostr;
        // } else {
        //     echo 111;
        //     file_put_contents("666666622222.txt",111111);
        //   exit("222");
        // }
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }
       
        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
       
        $out_trade_no = $data['out_trade_no'];
        $user_recharge = DB::name("user_recharge")->where("order_no",$out_trade_no)->find();
        if(empty($user_recharge)){
            return json(['code' => 'FAIL', 'message' => '订单有误'], 500, ['Content-Type' => 'application/json']);
        }
        if($user_recharge['status'] != 1){
            return json(['code' => 'FAIL', 'message' => '订单状态有误'], 500, ['Content-Type' => 'application/json']);
        }
        if($data['total_fee']/100 != $user_recharge['money']){
            return json(['code' => 'FAIL', 'message' => '订单有误'], 500, ['Content-Type' => 'application/json']);
        }
        
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            
            DB::name("user_recharge")->where("order_no",$out_trade_no)->update(array("status"=>2,"pay_time"=>date("Y-m-d H:i:s")));
            $user_find = DB::name("user")->where("id",$user_recharge['user_id'])->find();
            DB::name("user")->where("id",$user_recharge['user_id'])->setInc("money",$user_recharge['dou_money']);
            $money_data = array(
                "user_id" => $user_recharge['user_id'],
                "money" => $user_recharge['dou_money'],
                "before" => $user_find['money'],
                "after" => $user_find['money']+$user_recharge['dou_money'],
                "memo" => "充值".$user_recharge['money']."元获得".$user_recharge['dou_money']."嘶豆",
                "createtime" => time()
            );
            DB::name("user_money_log")->insert($money_data);
            
            //0329start
            $user_recharge_money = DB::name("user_recharge")->where(array("user_id"=>$user_recharge['user_id'],"status"=>2))->sum("money");
            $pow = pow($user_recharge_money, 1.0/3);
            $episode_usergood = DB::name("episode_usergood")->where(array("user_id"=>$user_recharge['user_id']))->select();
            foreach($episode_usergood as $key => $value) {
                if($value['num'] > 0){
                    $new_num = intval($pow*$value['num']);
                }elseif($value['num'] < 0){
                    $new_num = intval($pow);
                }else{
                    $new_num = 0;
                }
                DB::name("episode_usergood")->where("id",$value['id'])->update(array("pow_num"=>$new_num));
            }
            //0329end
            //0403end
            $system_level = DB::name("system_level")->where("money <=".$user_recharge_money)->order("level desc")->find();
            if($system_level){
                DB::name("user")->where("id",$user_recharge['user_id'])->update(array("level"=>$system_level['level']));
            }
            
            //0403end
            
            //0412start
            if($user_recharge['user_channel_id']){
                DB::name("user_channel")->where(array("id"=>$user_recharge['user_channel_id']))->setInc("money",$user_recharge['money']);
                DB::name("user_channel")->where(array("id"=>$user_recharge['user_channel_id']))->setInc("total_money",$user_recharge['money']);
                DB::name("user_channel")->where(array("id"=>$user_recharge['user_channel_id']))->setInc("today_recharge_num");
                DB::name("user_channel")->where(array("id"=>$user_recharge['user_channel_id']))->setInc("total_recharge_num");
            }
            //0412end
            
            //trackid有值代表此用户的渠道来源是B站，需要在支付成功以后向B站回传
            if($user_find['trackid']){
                $conv_value = bcmul($user_recharge['money'], 100);//转化的价值应该是用户付费的金额
                $conv_time = $this->getMillisecond();
                $track_id = $user_find['trackid'];
                if(!empty($track_id)){
//                    $track_id = "pbaes.pUNy4MJ2Ys480sM0UwZGtgegI02oMB26nQ0C1alN0X9S2qnwL5ZtrgEPnAOg9rUnS79cXwtXs-PVLkK2Xle3nwMVpDQUH5qSlPSvfSWMLY0WIzFfXB_PODxbOTucGwcDhZ2RhVap89IbWkhFX5xhzfk4alZMf3v8B3733EiwDKAQxekBf6iPPCR0fK3D1aaT";
                    //回传USER_COST
                    $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=USER_COST&conv_time=".$conv_time."&track_id=".$track_id."&conv_value=".$conv_value;
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                    $bili_res = file_get_contents($b_url);
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);

                    /**
                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                     */
                    $log_params = [
                        "user_id" => $user_find['id'],
                        "url" => $b_url,
                        "res" => $bili_res,
                        "trackid" => $track_id,
                        "company_entity" => $user_find['company_entity'],
                        "account" => $user_find['account'],
                    ];
                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$user_recharge['money']."元，给B站回传USER_COST");



                    //还要回传ORDER_PLACE
                    $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=ORDER_PLACE&conv_time=".$conv_time."&track_id=".$track_id."&conv_value=".$conv_value;
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                    $bili_res = file_get_contents($b_url);
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                    file_put_contents("log/notifyOrder_B".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);

                    /**
                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                     */
                    $log_params = [
                        "user_id" => $user_find['id'],
                        "url" => $b_url,
                        "res" => $bili_res,
                        "trackid" => $track_id,
                        "company_entity" => $user_find['company_entity'],
                        "account" => $user_find['account'],
                    ];
                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$user_recharge['money']."元，给B站回传ORDER_PLACE");
                }
            }

            //tencentid有值代表此用户的渠道来源是腾讯广告，需要在支付成功以后向腾讯回传
            if($user_find['tencentid']){
                //要向callback的地址提交一个post请求,先拿到callback地址,然后urldecode一下,最后上报注册信息
                $post_url = DB::name("cpa_teng_xun")->where('id','=',$user_find['tencentid'])->value('callback');
                $post_url = urldecode($post_url);
                $post_data['actions'] = [];
                $post_data['actions'][0]['action_type'] = "PURCHASE";
                $post_data['actions'][0]['action_time'] = time();
                $post_data['actions'][0]['user_id']['wechat_app_id'] = $this->AppId;
                $post_data['actions'][0]['user_id']['wechat_openid'] = $user_find['openid'];
                $post_data['actions'][0]['action_param']['value'] = $user_recharge['money'];

                file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);
                file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                $post_res = $this->json_post($post_url,$post_data);
                file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);
                file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);

                /**
                 * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                 */
                $log_params = [
                    "user_id" => $user_find['id'],
                    "url" => $post_url,
                    "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                    "res" => $post_res,
                    "tencentid" => $user_find['tencentid'],
                    "company_entity" => $user_find['company_entity'],
                    "account" => $user_find['account'],
                ];
                $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$user_recharge['money']."元，给广点通回传PURCHASE");
            }

            //clickid有值代表此用户的渠道来源是巨量引擎广告，需要在支付成功以后向巨量引擎广告回传
            if($user_find['clickid']){

                /**
                 * 现在有一个需求，每逢3笔，第3笔不回传给巨量引擎，是投流手和张老师那边提的
                 * 只针对巨量引擎的回传
                 */
                if(empty($user_find['account'])){
                    $cache_key = "juliangyinqin:account0:{$user_recharge['money']}";
                }else {
                    $cache_key = "juliangyinqin:{$user_find['account']}:{$user_recharge['money']}";
                }

                Cache::inc($cache_key);
                $cache_value = Cache::get($cache_key);
                if($cache_value % 3 == 0){//正好被3整除，余数为0，这一次就不回传

                }else {//否则正常回传
                    file_put_contents("log/notifyOrder_dy".date('Ymd').".txt","clickid=".$user_find['clickid'].PHP_EOL,FILE_APPEND);
                    $d_url = "https://ad.oceanengine.com/track/activate/?callback={$user_find['clickid']}&event_type=2";
                    $props = [];
                    $props['pay_amount'] = bcmul($user_recharge['money'], 100);//转化的价值应该是用户付费的金额
                    $props = json_encode($props);
                    $d_url .= "&props=".urlencode($props);
                    file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                    $dy_res = file_get_contents($d_url);
                    file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",$dy_res.PHP_EOL,FILE_APPEND);
                    file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                    file_put_contents("log/notifyOrder_dy".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);
                    /**
                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                     */
                    $log_params = [
                        "user_id" => $user_find['id'],
                        "url" => $d_url,
                        "res" => $dy_res,
                        "clickid" => $user_find['clickid'],
                        "clue_token" => $user_find['clue_token'],
                        "company_entity" => $user_find['company_entity'],
                        "account" => $user_find['account'],
                    ];
                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$user_recharge['money']."元，给巨量引擎回传event_type=2表示付费");
                }
            }

            //如果有clue_token字段，则表示用户是星图达人来源的，付款时要回传数据
            //之所以加empty($user_find['clickid'])是为了防止巨量引擎平台重复回传
            if(empty($user_find['clickid']) && $user_find['clue_token']){
                $post_url = "https://clue.oceanengine.com/outer/wechat/applet/token/1794573964023881";

                $token = "DA4F57B4A91927287BDB4C22CA1D9817";
                $nonce = rand(10000,99999);//随机整数，防止请求被中间劫持篡改
                $timestamp = time();//当前时间戳

                $collect = [
                    (string)$token,(string)$nonce,(string)$timestamp,
                ];

                usort($collect,'strcmp');
                $signature = sha1(implode('',$collect));

                $post_url .= "?timestamp={$timestamp}&nonce={$nonce}&signature={$signature}";
                file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);


                $post_data = [];
                $post_data['clue_token'] = (string)$user_find['clue_token'];
                $post_data['open_id'] = (string)$user_find['openid'];
                $post_data['event_type'] = "2";//2-付费
                $post_data['props']['pay_amount'] = (int)bcmul($user_recharge['money'], 100);
                $post_res = $this->json_post($post_url,$post_data);
                file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                file_put_contents("log/notifyOrder_zj".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);

                /**
                 * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                 */
                $log_params = [
                    "user_id" => $user_find['id'],
                    "url" => $post_url,
                    "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                    "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                    "clickid" => $user_find['clickid'],
                    "clue_token" => $user_find['clue_token'],
                    "company_entity" => $user_find['company_entity'],
                    "account" => $user_find['account'],
                ];
                $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$user_recharge['money']."元，给巨量星图回传event_type=2表示付费");
            }
            
            //end
            
            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
    
    public function ceshi(){
        echo "success";
		return json(['code'=>1,'data'=>'','mag'=>'成功']);
	}
    public function tosetInterval(){
        while(true){
            $this->notifyXnOrder();
            sleep(5);
        }
    }
    
    
    /**
     * 支付成功【虚拟微信小程序】
     */
    public function notifyXnOrder()
    {
        try {
           // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
            // 如果是基础库的wx.requestVirtualPayment，uri固定为requestVirtualPayment
            $uri = '/xpay/query_order';
            $appkey = "SgM7386iqymWi0qrj7ReIn7CbgRqLjBA";
            $user_recharge_list = DB::name("user_recharge")->where(array("status"=>1,"type"=>1,"device_type"=>1))->select();
            if($user_recharge_list){
                foreach($user_recharge_list as $key => $val){
                    $user_find = DB::name("user")->where("id",$val['user_id'])->find();
                    $data = array(
                        "openid" => $user_find['openid'],
                        "env" => 0,
                        "order_id" => $val['order_no'],
                        "wx_order_id" => "",
                    );
                    // 
                    $post_body = json_encode($data);
                    $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
                    $access_token = $this->get_access_token();
                    // print_r($access_token);exit;
                    $url = 'https://api.weixin.qq.com/xpay/query_order?access_token='.$access_token.'&pay_sig='.$pay_sig;
                    $json_res = $this->json_post($url,$data);
                    $res = json_decode($json_res,true);


                    /**
                     * 由于微信的虚拟支付经常会返回一些status=0，status=6，errcode=268490003，errcode=268490002，但这些数据里面又混杂着用户真的付钱了的订单
                     * 所以针对这些回传的数据，再做一次查询
                     * {"errcode":268490003,"errmsg":"支付签名(pay_sig)校验失败 rid: 6633ca0c-3c5d4974-2d04132e"}
                     * {"errcode":268490002,"errsg":"数据不存在 rid: 6634300a-6c6a9578-33868b65"}
                     * {"errcode":0,"errmsg":"OK","order":{"order_id":"recharge202405030029524327","create_time":1714667393,"update_time":1714667399,"status":6,"biz_type":0,"order_fee":9990,"order_type":0,"biz_meta":"{\"attach\":\"testdata\"}","env_type":1,"token":"E-240503001137842644","wx_order_id":"VPO240503002953050892057","sett_time":0,"sett_state":0}}
                     * {"errcode":0,"errmsg":"OK","order":{"order_id":"recharge202405030355008568","create_time":1714679700,"update_time":1714679700,"status":0,"biz_type":0,"order_fee":3990,"order_type":0,"biz_meta":"{\"attach\":\"testdata\"}","env_type":1,"wx_order_id":"VPO240503035500020397482","sett_time":0,"sett_state":0}}
                     */
                    if(in_array($res['errcode'],[268490003,268490002])){
                        //再尝试获取一次
                        $data = array(
                            "openid" => $user_find['openid'],
                            "env" => 0,
                            "order_id" => $val['order_no'],
                            "wx_order_id" => "",
                        );
                        //
                        $post_body = json_encode($data);
                        $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
                        $access_token = $this->get_access_token();
                        $url = 'https://api.weixin.qq.com/xpay/query_order?access_token='.$access_token.'&pay_sig='.$pay_sig;
                        $json_res = $this->json_post($url,$data);
                        $res = json_decode($json_res,true);
                    }else if($res['errcode'] == 0 && in_array($res['order']['status'],[0,6])){
                        //再尝试获取一次
                        $data = array(
                            "openid" => $user_find['openid'],
                            "env" => 0,
                            "order_id" => $val['order_no'],
                            "wx_order_id" => "",
                        );
                        //
                        $post_body = json_encode($data);
                        $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
                        $access_token = $this->get_access_token();
                        $url = 'https://api.weixin.qq.com/xpay/query_order?access_token='.$access_token.'&pay_sig='.$pay_sig;
                        $json_res = $this->json_post($url,$data);
                        $res = json_decode($json_res,true);
                    }



                    if($res['errcode'] != 0){
                        DB::name("user_recharge")->where(array("id"=>$val['id']))->update(array("status"=>3,"back_json"=>$json_res));
                    }else{
                        $order = $res['order'];
                        if($order['status'] != 1 && $order['status'] != 2 && $order['status'] != 3 && $order['status'] != 4){
                            DB::name("user_recharge")->where(array("id"=>$val['id']))->update(array("status"=>3,"back_json"=>$json_res));
                        }else{
                            if($order['status'] != 1){
                                DB::name("user_recharge")->where("order_no",$val['order_no'])->update(array("status"=>2,"back_json"=>$json_res,"pay_time"=>date("Y-m-d H:i:s")));
                                $user_find = DB::name("user")->where("id",$val['user_id'])->find();
                                DB::name("user")->where("id",$val['user_id'])->setInc("money",$val['dou_money']);
                                $money_data = array(
                                    "user_id" => $val['user_id'],
                                    "money" => $val['dou_money'],
                                    "before" => $user_find['money'],
                                    "after" => $user_find['money']+$val['dou_money'],
                                    "memo" => "充值".$val['money']."元获得".$val['dou_money']."嘶豆",
                                    "createtime" => time()
                                );
                                DB::name("user_money_log")->insert($money_data);
                                
                                //0329start
                                $user_recharge_money = DB::name("user_recharge")->where(array("user_id"=>$val['user_id'],"status"=>2))->sum("money");
                                $pow = pow($user_recharge_money, 1.0/3);
                                $episode_usergood = DB::name("episode_usergood")->where(array("user_id"=>$val['user_id']))->select();
                                foreach($episode_usergood as $key => $value) {
                                    if($value['num'] > 0){
                                        $new_num = intval($pow*$value['num']);
                                    }elseif($value['num'] < 0){
                                        $new_num = intval($pow);
                                    }else{
                                        $new_num = 0;
                                    }
                                    DB::name("episode_usergood")->where("id",$value['id'])->update(array("pow_num"=>$new_num));
                                }
                                //0329end
                                //0403end
                                $system_level = DB::name("system_level")->where("money <=".$user_recharge_money)->order("level desc")->find();
                                if($system_level){
                                    DB::name("user")->where("id",$val['user_id'])->update(array("level"=>$system_level['level']));
                                }
                                
                                //0403end

                                //0412start
                                if($val['user_channel_id']){
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("money",$val['money']);
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("total_money",$val['money']);
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("today_recharge_num");
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("total_recharge_num");
                                }
                                //0412end
                                
                                //trackid有值代表此用户的渠道来源是B站，需要在支付成功以后向B站回传
                                if($user_find['trackid']){
                                    $conv_value = bcmul($val['money'], 100);//转化的价值应该是用户付费的金额
                                    $conv_time = $this->getMillisecond();
                                    $track_id = $user_find['trackid'];
                                    if(!empty($track_id)){
                    //                    $track_id = "pbaes.pUNy4MJ2Ys480sM0UwZGtgegI02oMB26nQ0C1alN0X9S2qnwL5ZtrgEPnAOg9rUnS79cXwtXs-PVLkK2Xle3nwMVpDQUH5qSlPSvfSWMLY0WIzFfXB_PODxbOTucGwcDhZ2RhVap89IbWkhFX5xhzfk4alZMf3v8B3733EiwDKAQxekBf6iPPCR0fK3D1aaT";
                                        $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=USER_COST&conv_time=".$conv_time."&track_id=".$track_id."&conv_value=".$conv_value;
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                        $bili_res = file_get_contents($b_url);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "user_id" => $user_find['id'],
                                            "url" => $b_url,
                                            "res" => $bili_res,
                                            "trackid" => $track_id,
                                            "company_entity" => $user_find['company_entity'],
                                            "account" => $user_find['account'],
                                        ];
                                        $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给B站回传USER_COST");



                                        //还要回传ORDER_PLACE
                                        $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=ORDER_PLACE&conv_time=".$conv_time."&track_id=".$track_id."&conv_value=".$conv_value;
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                        $bili_res = file_get_contents($b_url);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "user_id" => $user_find['id'],
                                            "url" => $b_url,
                                            "res" => $bili_res,
                                            "trackid" => $track_id,
                                            "company_entity" => $user_find['company_entity'],
                                            "account" => $user_find['account'],
                                        ];
                                        $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给B站回传ORDER_PLACE");
                                    }
                                }

                                //tencentid有值代表此用户的渠道来源是腾讯广告，需要在支付成功以后向腾讯回传
                                if($user_find['tencentid']){
                                    //要向callback的地址提交一个post请求,先拿到callback地址,然后urldecode一下,最后上报注册信息
                                    $post_url = DB::name("cpa_teng_xun")->where('id','=',$user_find['tencentid'])->value('callback');
                                    $post_url = urldecode($post_url);
                                    $post_data['actions'] = [];
                                    $post_data['actions'][0]['action_type'] = "PURCHASE";
                                    $post_data['actions'][0]['action_time'] = time();
                                    $post_data['actions'][0]['user_id']['wechat_app_id'] = $this->AppId;
                                    $post_data['actions'][0]['user_id']['wechat_openid'] = $user_find['openid'];
                                    $post_data['actions'][0]['action_param']['value'] = $val['money'];

                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "user_id" => $user_find['id'],
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => $post_res,
                                        "tencentid" => $user_find['tencentid'],
                                        "company_entity" => $user_find['company_entity'],
                                        "account" => $user_find['account'],
                                    ];
                                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给广点通回传PURCHASE");
                                }

                                //clickid有值代表此用户的渠道来源是抖音，需要在支付成功以后向抖音回传
                                if($user_find['clickid']){

                                    /**
                                     * 现在有一个需求，每逢3笔，第3笔不回传给巨量引擎，是投流手和张老师那边提的
                                     * 只针对巨量引擎的回传
                                     */
                                    if(empty($user_find['account'])){
                                        $cache_key = "juliangyinqin:account0:{$val['money']}";
                                    }else {
                                        $cache_key = "juliangyinqin:{$user_find['account']}:{$val['money']}";
                                    }

                                    Cache::inc($cache_key);
                                    $cache_value = Cache::get($cache_key);
                                    if($cache_value % 3 == 0) {//正好被3整除，余数为0，这一次就不回传

                                    }else {
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt","clickid=".$user_find['clickid'].PHP_EOL,FILE_APPEND);

                                        $d_url = "https://ad.oceanengine.com/track/activate/?callback={$user_find['clickid']}&event_type=2";

                                        $props = [];

                                        $props['pay_amount'] = bcmul($val['money'], 100);//转化的价值应该是用户付费的金额
                                        $props = json_encode($props);

                                        $d_url .= "&props=".urlencode($props);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                                        $dy_res = file_get_contents($d_url);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",$dy_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);
                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "user_id" => $user_find['id'],
                                            "url" => $d_url,
                                            "res" => $dy_res,
                                            "clickid" => $user_find['clickid'],
                                            "clue_token" => $user_find['clue_token'],
                                            "company_entity" => $user_find['company_entity'],
                                            "account" => $user_find['account'],
                                        ];
                                        $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给巨量引擎回传event_type=2表示付费");

                                    }
                                }

                                //如果有clue_token字段，则表示用户是字节的巨量来源的，付款时要回传数据
                                //之所加empty($user_find['clickid'])是为了防止巨量引擎重复回传金额
                                if(empty($user_find['clickid']) && $user_find['clue_token']){
                                    $post_url = "https://clue.oceanengine.com/outer/wechat/applet/token/1794573964023881";

                                    $token = "DA4F57B4A91927287BDB4C22CA1D9817";
                                    $nonce = rand(10000,99999);//随机整数，防止请求被中间劫持篡改
                                    $timestamp = time();//当前时间戳

                                    $collect = [
                                        (string)$token,(string)$nonce,(string)$timestamp,
                                    ];

                                    usort($collect,'strcmp');
                                    $signature = sha1(implode('',$collect));

                                    $post_url .= "?timestamp={$timestamp}&nonce={$nonce}&signature={$signature}";
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);


                                    $post_data = [];
                                    $post_data['clue_token'] = (string)$user_find['clue_token'];
                                    $post_data['open_id'] = (string)$user_find['openid'];
                                    $post_data['event_type'] = "2";//2-付费
                                    $post_data['props']['pay_amount'] = (int)bcmul($val['money'], 100);
                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);



//                                    $notify_order_zj_insert_data = [];
//                                    $notify_order_zj_insert_data['user_id'] = $user_find['id'];
//                                    $notify_order_zj_insert_data['clue_token'] = $user_find['clue_token'];
//                                    $notify_order_zj_insert_data['url'] = $post_url;
//                                    $notify_order_zj_insert_data['money'] = $val['money'];
//                                    $notify_order_zj_insert_data['back_json'] = json_encode($post_res,JSON_UNESCAPED_UNICODE);
//                                    $notify_order_zj_insert_data['createtime'] = date('Y-m-d H:i:s');
//
//                                    DB::name("notify_order_zj")->insert($notify_order_zj_insert_data);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "user_id" => $user_find['id'],
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                                        "clickid" => $user_find['clickid'],
                                        "clue_token" => $user_find['clue_token'],
                                        "company_entity" => $user_find['company_entity'],
                                        "account" => $user_find['account'],
                                    ];
                                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给巨量星图回传event_type=2表示付费");

                                }
                                
                                //扣除虚拟支付的余额
                                $uri = '/xpay/currency_pay';
                                $data = array(
                                    "openid" => $user_find['openid'],
                                    "env" => 0,
                                    "user_ip" => $_SERVER['REMOTE_ADDR'],
                                    "amount" => ceil($val['money']*100),
                                    "order_id" => $val['order_no'],
                                    "payitem" => "testpayitem",
                                    "remark" => "testremark",
                                    "device_type" => 1,
                                );
                                // 
                                $post_body = json_encode($data);
                                $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
                                $access_token = $this->get_access_token();
                                $signature = $this->calc_signature($post_body, $user_find['session_key']);
                                // print_r($access_token);exit;
                                $url = 'https://api.weixin.qq.com/xpay/currency_pay?access_token='.$access_token.'&pay_sig='.$pay_sig.'&signature='.$signature;
                                $res = json_decode($this->json_post($url,$data),true);
                                file_put_contents("testW1111.txt",var_export($res,true),FILE_APPEND);
                                
                            }
                        }
                    }
                }
            }


            // \think\Log::record($data);
            // //获取支付金额、订单号
            // $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            
            
            
            // //end
            
            // \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }
        return json(['code'=>1,'data'=>'','mag'=>'成功']);
        

        //下面这句必须要执行,且在此之前不能有任何输出
        // if (Service::isVersionV3()) {
        //     return $pay->success()->getBody()->getContents();
        // } else {
        //     return $pay->success()->send();
        // }
    }
    function calc_pay_sig($uri, $post_body, $appkey) {
        // pay_sig签名算法
        $need_sign_msg = $uri . '&' . $post_body;
        $pay_sig = hash_hmac('sha256', $need_sign_msg, $appkey);
        return $pay_sig;
    }
    function calc_signature($post_body, $session_key) {
        // 用户登录态signature签名算法
        $need_sign_msg = $post_body;
        $signature = hash_hmac('sha256', $need_sign_msg, $session_key);
        return $signature;
    }
    
    //获取小程序二维码的token
    public function get_access_token()
    {
        //先判断缓存里面的access_token过期了没有
        if(Cache::get('access_token')){
            //没过期直接拿出来用
            $a = Cache::get('access_token');
            return $a;
        }else{
            //过期了就重新获取
            $appid = 'wxbae1b3248b60e1d8';
            $secret = 'b3df3f25537d5c1cdd9ac67e47b7391c';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            
            //请求接口，获取accesstoken
            $user_obj = $this->curlHttp($url);
            //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
            Cache::set('access_token',$user_obj['access_token'],900);

            return Cache::get('access_token');
        }
    }

    function curlHttp($url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return json_decode($output, true);
    }
    
    /**
     * 获取时间戳到毫秒
     * @return bool|string
     */
    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime,0,13);
    }
    
    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }

    /**
     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
     * @param $log_params 记录数据信息
     * @param $remark 备注
     * @return int|string
     */
    protected function save_touliushou_log($log_params = [],$remark = "")
    {
        if(isset($log_params['share_type'])){
            $data['share_type'] = $log_params['share_type'];
        }
        if(isset($log_params['share_code'])){
            $data['share_code'] = $log_params['share_code'];
        }
        if(isset($log_params['url'])){
            $data['url'] = $log_params['url'];
        }
        if(isset($log_params['data'])){
            $data['data'] = $log_params['data'];
        }
        if(isset($log_params['res'])){
            $data['res'] = $log_params['res'];
        }
        if(isset($log_params['trackid'])){
            $data['trackid'] = $log_params['trackid'];
        }
        if(isset($log_params['tencentid'])){
            $data['tencentid'] = $log_params['tencentid'];
        }
        if(isset($log_params['clickid'])){
            $data['clickid'] = $log_params['clickid'];
        }
        if(isset($log_params['clue_token'])){
            $data['clue_token'] = $log_params['clue_token'];
        }
        if(isset($log_params['company_entity'])){
            $data['company_entity'] = $log_params['company_entity'];
        }
        if(isset($log_params['account'])){
            $data['account'] = $log_params['account'];
        }
        if(isset($log_params['user_id'])){
            $data['user_id'] = $log_params['user_id'];
        }
        if($remark){
            $data['remark'] = $remark;
        }
        $data['create_time'] = date("Y-m-d H:i:s");
        $res = DB::name("touliushou_log")->insert($data);
        return $res;
    }
    
     /**
     * 支付成功【抖音小程序】
     */
    public function notifyDyOrder()
    {
        try {
           
            $user_recharge_list = DB::name("user_recharge")->where(array("status"=>1,"type"=>2,"device_type"=>1))->select();
            if($user_recharge_list){
                foreach($user_recharge_list as $key => $val){

                    $url = 'https://open.douyin.com/api/trade_basic/v1/developer/order_query/';
                    $data = array(
                        "order_id" => '',
                        "out_order_no" => $val['order_no'],
                        "access_token" => $this->get_dy_access_token()
                    );
                    $json_res = $this->json_token_post($url,$data);
                    $res = json_decode($json_res,true);
                    if($res['err_no'] == '28001008'){
                        $data = array(
                            "order_id" => '',
                            "out_order_no" => $val['order_no'],
                            "access_token" => $this->get_new_dy_access_token()
                        );
                        $json_res = $this->json_token_post($url,$data);
                        $res = json_decode($json_res,true);
                    }
                    
                    if($res['err_no'] != 0){
                        DB::name("user_recharge")->where(array("id"=>$val['id']))->update(array("status"=>3,"back_json"=>$json_res));
                    }else{
                        $order = $res['data'];
                        if($order['pay_status'] != 'SUCCESS' && $order['pay_status'] != 'PROCESS'){
                            DB::name("user_recharge")->where(array("id"=>$val['id']))->update(array("status"=>3,"back_json"=>$json_res));
                        }else{
                            if($order['pay_status'] == 'SUCCESS'){
                                DB::name("user_recharge")->where("order_no",$val['order_no'])->update(array("status"=>2,"back_json"=>$json_res,"pay_time"=>date("Y-m-d H:i:s")));
                                $user_find = DB::name("user")->where("id",$val['user_id'])->find();
                                DB::name("user")->where("id",$val['user_id'])->setInc("money",$val['dou_money']);
                                $money_data = array(
                                    "user_id" => $val['user_id'],
                                    "money" => $val['dou_money'],
                                    "before" => $user_find['money'],
                                    "after" => $user_find['money']+$val['dou_money'],
                                    "memo" => "充值".$val['money']."元获得".$val['dou_money']."嘶豆",
                                    "createtime" => time()
                                );
                                DB::name("user_money_log")->insert($money_data);
                                
                                $user_recharge_money = DB::name("user_recharge")->where(array("user_id"=>$val['user_id'],"status"=>2))->sum("money");
                                $pow = pow($user_recharge_money, 1.0/3);
                                $episode_usergood = DB::name("episode_usergood")->where(array("user_id"=>$val['user_id']))->select();
                                foreach($episode_usergood as $key => $value) {
                                    if($value['num'] > 0){
                                        $new_num = intval($pow*$value['num']);
                                    }elseif($value['num'] < 0){
                                        $new_num = intval($pow);
                                    }else{
                                        $new_num = 0;
                                    }
                                    DB::name("episode_usergood")->where("id",$value['id'])->update(array("pow_num"=>$new_num));
                                }
                                $system_level = DB::name("system_level")->where("money <=".$user_recharge_money)->order("level desc")->find();
                                if($system_level){
                                    DB::name("user")->where("id",$val['user_id'])->update(array("level"=>$system_level['level']));
                                }
                                
                                if($val['user_channel_id']){
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("money",$val['money']);
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("total_money",$val['money']);
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("today_recharge_num");
                                    DB::name("user_channel")->where(array("id"=>$val['user_channel_id']))->setInc("total_recharge_num");
                                }
                                
                                //trackid有值代表此用户的渠道来源是B站，需要在支付成功以后向B站回传
                                if($user_find['trackid']){
                                    $conv_value = bcmul($val['money'], 100);//转化的价值应该是用户付费的金额
                                    $conv_time = $this->getMillisecond();
                                    $track_id = $user_find['trackid'];
                                    if(!empty($track_id)){
                                    // $track_id = "pbaes.pUNy4MJ2Ys480sM0UwZGtgegI02oMB26nQ0C1alN0X9S2qnwL5ZtrgEPnAOg9rUnS79cXwtXs-PVLkK2Xle3nwMVpDQUH5qSlPSvfSWMLY0WIzFfXB_PODxbOTucGwcDhZ2RhVap89IbWkhFX5xhzfk4alZMf3v8B3733EiwDKAQxekBf6iPPCR0fK3D1aaT";
                                        $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=USER_COST&conv_time=".$conv_time."&track_id=".$track_id."&conv_value=".$conv_value;
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                        $bili_res = file_get_contents($b_url);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "user_id" => $user_find['id'],
                                            "url" => $b_url,
                                            "res" => $bili_res,
                                            "trackid" => $track_id,
                                            "company_entity" => $user_find['company_entity'],
                                            "account" => $user_find['account'],
                                        ];
                                        $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给B站回传USER_COST");



                                        //还要回传ORDER_PLACE
                                        $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=ORDER_PLACE&conv_time=".$conv_time."&track_id=".$track_id."&conv_value=".$conv_value;
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                        $bili_res = file_get_contents($b_url);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_B".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "user_id" => $user_find['id'],
                                            "url" => $b_url,
                                            "res" => $bili_res,
                                            "trackid" => $track_id,
                                            "company_entity" => $user_find['company_entity'],
                                            "account" => $user_find['account'],
                                        ];
                                        $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给B站回传ORDER_PLACE");
                                    }
                                }

                                //tencentid有值代表此用户的渠道来源是腾讯广告，需要在支付成功以后向腾讯回传
                                if($user_find['tencentid']){
                                    //要向callback的地址提交一个post请求,先拿到callback地址,然后urldecode一下,最后上报注册信息
                                    $post_url = DB::name("cpa_teng_xun")->where('id','=',$user_find['tencentid'])->value('callback');
                                    $post_url = urldecode($post_url);
                                    $post_data['actions'] = [];
                                    $post_data['actions'][0]['action_type'] = "PURCHASE";
                                    $post_data['actions'][0]['action_time'] = time();
                                    $post_data['actions'][0]['user_id']['wechat_app_id'] = $this->AppId;
                                    $post_data['actions'][0]['user_id']['wechat_openid'] = $user_find['openid'];
                                    $post_data['actions'][0]['action_param']['value'] = $val['money'];

                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_gdt".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "user_id" => $user_find['id'],
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => $post_res,
                                        "tencentid" => $user_find['tencentid'],
                                        "company_entity" => $user_find['company_entity'],
                                        "account" => $user_find['account'],
                                    ];
                                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给广点通回传PURCHASE");
                                }

                                //clickid有值代表此用户的渠道来源是抖音，需要在支付成功以后向抖音回传
                                if($user_find['clickid']){

                                    /**
                                     * 现在有一个需求，每逢3笔，第3笔不回传给巨量引擎，是投流手和张老师那边提的
                                     * 只针对巨量引擎的回传
                                     */
                                    if(empty($user_find['account'])){
                                        $cache_key = "juliangyinqin:account0:{$val['money']}";
                                    }else {
                                        $cache_key = "juliangyinqin:{$user_find['account']}:{$val['money']}";
                                    }

                                    Cache::inc($cache_key);
                                    $cache_value = Cache::get($cache_key);
                                    if($cache_value % 3 == 0) {//正好被3整除，余数为0，这一次就不回传

                                    }else {
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt","clickid=".$user_find['clickid'].PHP_EOL,FILE_APPEND);

                                        $d_url = "https://ad.oceanengine.com/track/activate/?callback={$user_find['clickid']}&event_type=2";

                                        $props = [];

                                        $props['pay_amount'] = bcmul($val['money'], 100);//转化的价值应该是用户付费的金额
                                        $props = json_encode($props);

                                        $d_url .= "&props=".urlencode($props);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                                        $dy_res = file_get_contents($d_url);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",$dy_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/notifyOrder_dy".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "user_id" => $user_find['id'],
                                            "url" => $d_url,
                                            "res" => $dy_res,
                                            "clickid" => $user_find['clickid'],
                                            "clue_token" => $user_find['clue_token'],
                                            "company_entity" => $user_find['company_entity'],
                                            "account" => $user_find['account'],
                                        ];
                                        $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给巨量引擎回传event_type=2表示付费");
                                    }
                                }

                                //如果有clue_token字段，则表示用户是字节的巨量来源的，付款时要回传数据
                                //之所以加empty($user_find['clickid'])是为了防止巨量引擎重复回传金额
                                if(empty($user_find['clickid']) && $user_find['clue_token']){
                                    $post_url = "https://clue.oceanengine.com/outer/wechat/applet/token/1794573964023881";

                                    $token = "DA4F57B4A91927287BDB4C22CA1D9817";
                                    $nonce = rand(10000,99999);//随机整数，防止请求被中间劫持篡改
                                    $timestamp = time();//当前时间戳

                                    $collect = [
                                        (string)$token,(string)$nonce,(string)$timestamp,
                                    ];

                                    usort($collect,'strcmp');
                                    $signature = sha1(implode('',$collect));

                                    $post_url .= "?timestamp={$timestamp}&nonce={$nonce}&signature={$signature}";
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);


                                    $post_data = [];
                                    $post_data['clue_token'] = (string)$user_find['clue_token'];
                                    $post_data['open_id'] = (string)$user_find['openid'];
                                    $post_data['event_type'] = "2";//2-付费
                                    $post_data['props']['pay_amount'] = (int)bcmul($val['money'], 100);
                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/notifyOrder_zj".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);



                                    //  $notify_order_zj_insert_data = [];
                                    //  $notify_order_zj_insert_data['user_id'] = $user_find['id'];
                                    //   $notify_order_zj_insert_data['clue_token'] = $user_find['clue_token'];
                                    //   $notify_order_zj_insert_data['url'] = $post_url;
                                    //   $notify_order_zj_insert_data['money'] = $val['money'];
                                    //   $notify_order_zj_insert_data['back_json'] = json_encode($post_res,JSON_UNESCAPED_UNICODE);
                                    //  $notify_order_zj_insert_data['createtime'] = date('Y-m-d H:i:s');
                                    //
                                    //  DB::name("notify_order_zj")->insert($notify_order_zj_insert_data);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "user_id" => $user_find['id'],
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                                        "clickid" => $user_find['clickid'],
                                        "clue_token" => $user_find['clue_token'],
                                        "company_entity" => $user_find['company_entity'],
                                        "account" => $user_find['account'],
                                    ];
                                    $this->save_touliushou_log($log_params,"用户付费行为，付了￥".$val['money']."元，给巨量星图回传event_type=2表示付费");

                                }
                                
                                
                            }
                            // else{
                            //     echo 1111;
                            // }
                        }
                    }

                    $user_find = DB::name("user")->where("id",$val['user_id'])->find();
                   
                }
            }

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }
        return json(['code'=>1,'data'=>'','mag'=>'成功']);
    }


    /**
     * 发送post请求
     */
    function json_token_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $access_token = $data['access_token'];
        unset($data['access_token']);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json',
            'access-token: '.$access_token,
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

    
    //获取小程序二维码的token
    public function get_dy_access_token()
    {
        //先判断缓存里面的access_token过期了没有
        if(Cache::get('dy_access_token')){
            //没过期直接拿出来用
            $a = Cache::get('dy_access_token');
            return $a;
        }else{
           //过期了就重新获取
            $client_key = 'tte3e2955f7cd2a7d301';
            $client_secret = '1a8c380ad5fa5b6e3d0455604c47eecf34ba2038';
            $grant_type = 'client_credential';
            $url = "https://open-sandbox.douyin.com/oauth/client_token/";
            $data = array(
                "client_key" => $client_key,
                "client_secret" => $client_secret,
                "grant_type" => $grant_type,
            );
            //请求接口，获取accesstoken
            $user_obj = json_decode($this->get_dy_client_token($url,$data),true);
            // print_r($user_obj['data']);exit;
            //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
            Cache::set('dy_access_token',$user_obj['data']['access_token'],900);
            return Cache::get('dy_access_token');
        }
    }
    //获取抖音小程序二维码的token
    public function get_new_dy_access_token()
    {
        //过期了就重新获取
        $client_key = 'tte3e2955f7cd2a7d301';
        $client_secret = '1a8c380ad5fa5b6e3d0455604c47eecf34ba2038';
        $grant_type = 'client_credential';
        $url = "https://open-sandbox.douyin.com/oauth/client_token/";
        $data = array(
            "client_key" => $client_key,
            "client_secret" => $client_secret,
            "grant_type" => $grant_type,
        );
        //请求接口，获取accesstoken
        $user_obj = json_decode($this->get_dy_client_token($url,$data),true);
        //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
        Cache::set('dy_access_token',$user_obj['access_token'],900);

        return Cache::get('dy_access_token');
    }

    /**
     * 发送post请求
     */
    function get_dy_client_token($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json',
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

    
}
